package com.service.business.support;

import com.alibaba.fastjson.JSONObject;
import com.service.dao.po.MemberCache;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <dl>
 * <dt>platform</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2018</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019-04-26</dd>
 * </dl>
 */
@Component
public class MemberCacheUtils {


    private static String member_performance = "MEMBER_PERFORMANCE_";



    @Autowired
    private MemCache memCache;

    public BigDecimal getSomedayGiftOrderTotalMoney(Integer memberId, Date someday) {
        String totalMoney = memCache.get(this.buildSomedayGiftOrderKey(memberId, someday));
        if (StringUtils.isBlank(totalMoney)) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(Double.parseDouble(totalMoney));
    }

    public void setSomedayGiftOrderTotalMoney(Integer memberId, Date someday, @NonNull BigDecimal payMoney) {
        BigDecimal totalMoney = getSomedayGiftOrderTotalMoney(memberId, someday);
        memCache.setNoExpire(buildSomedayGiftOrderKey(memberId, someday), totalMoney.add(payMoney).toString());
    }

    public void removeSomedayGiftOrderTotalMoney(Integer memberId, Date someday) {
        memCache.delete(buildSomedayGiftOrderKey(memberId, someday));
    }

    private String buildSomedayGiftOrderKey(Integer memberId, Date someday) {
        String date_pattern = "yyyy_MM_dd_";
        return "gift_order_total_money_" + DateFormatUtils.format(someday, date_pattern) + memberId;
    }

    public MemberCache getMemberCache(Integer memberId) {
        String memberCache = memCache.get(member_performance + memberId);
        return JSONObject.parseObject(memberCache, MemberCache.class);
    }

    public void setMemberCache(MemberCache memberCache) {
        memCache.setNoExpire(member_performance + memberCache.getMemberId(), JSONObject.toJSONString(memberCache));
    }
}
